<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <Row>
      <Col :span="7">
        <div class="left-panel">
          <Card class="left-card">
            <div class="task-type-selector">
              <div class="task-type-label">任务类型</div>
              <RadioGroup v-model:value="selectValue">
                <Radio value="Video">视频评论任务</Radio>
                <Radio value="Chat">人员匹配任务</Radio>
                <div class="fast-task">
                  <Radio value="fast">一键分发任务</Radio>
                </div>
              </RadioGroup>
            </div>
            <!-- //视频任务列表 -->
            <VideoFrom v-if="selectValue == 'Video'" ref="videoFromRef"></VideoFrom>
            <BasicForm v-if="selectValue == 'Chat'" @register="registerFormChat">
              <template #advertisementTemplate>
                <Select
                  ref="select"
                  v-model:value="advertisementTemplate"
                  style="width: 100%"
                  @change="fetchTemplateDetail"
                  placeholder="请选择模板"
                >
                  <SelectOption
                    v-for="option in templateList"
                    :key="option.id"
                    :value="option.remark"
                  >
                  </SelectOption>
                </Select>
              </template>
            </BasicForm>
            <BasicForm v-if="selectValue == 'fast'" @register="chatregisterForm"> </BasicForm>
            <BasicForm @register="registerFormChatTime" v-if="selectValue == 'Video'"></BasicForm>
            <div class="selected-video-info" v-if="selectValue != 'fast'">
              <span v-if="checkNum.length == 0">您暂未选择视频</span>
              <span v-else>您勾选了{{ checkNum.length }}条视频</span>
            </div>
            <div class="task-button-container" v-if="selectValue == 'fast'">
              <a-button type="primary" :loading="loading" @click="handleOKfast">发布任务</a-button>
            </div>
            <div class="task-button-container" v-else>
              <a-button type="primary" :loading="loading" @click="handleOK">发布任务</a-button>
            </div>
          </Card>
        </div>
      </Col>
      <Col :span="17">
        <div class="right-panel">
          <Card>
            <BasicTable @register="registerTableModel">
              <template #toolbar>
                <div class="toolbar">
                  <div class="toolbar-label">勾选前</div>
                  <div class="toolbar-input">
                    <Input v-model:value="dataIdList"></Input>
                  </div>
                  <div class="toolbar-label">条视频</div>
                  <a-button type="primary" @click="check" :loading="loading">确认勾选</a-button>
                  <a-button @click="Clear">取消勾选</a-button>
                </div>
              </template>
            </BasicTable>
          </Card>
        </div>
      </Col>
    </Row>
    <AccountModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import {
    Tooltip,
    Select,
    SelectOption,
    RadioGroup,
    Radio,
    message,
    Card,
    Row,
    Col,
    Input,
  } from 'ant-design-vue';
  import { useModal } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicTable, useTable } from '@/components/Table';
  import { PageWrapper } from '@/components/Page';
  import {
    columnsModels,
    searchFormSchema,
    accountFormChat,
    accountFormChatTime,
    chatAccountFormSchema,
  } from './account.data';
  import AccountModal from './AccountModal.vue';
  import {
    getMatchCategoryPageAPI,
    getdeviceToOwnerAPI,
    getMatchCategoryPageAPICheck,
    getCommentMarchPageAPI,
  } from '@/api/demo/videoList';
  import VideoFrom from './videoFrom.vue';
  import { getAudiencesListAPI } from '@/api/demo/template';
  import { createTaskApi } from '@/api/demo/Task';
  import { createTaskChat } from '@/api/demo/chat';
  import { SubcreateTaskAPI } from '@/api/demo/InformationMatching';
  import { useI18n } from '@/hooks/web/useI18n';

  const { t } = useI18n();
  const templateList = ref<any[]>([]);
  const deviceList = ref<any[]>([]);
  const videoFromRef = ref(null); // 定义 ref 来引用子组件
  const links = ref([]);
  const dataIdList = ref('');
  const checkNum = ref<any[]>([]);
  const loading = ref(false); // 控制按钮加载状态
  const advertisementTemplate = ref(null);
  const selectValue = ref('Video');
  const deviceValue = ref([]);
  const searchInfo = reactive<Recordable>({});
  const [registerModal, { openModal }] = useModal();
  interface TableRow {
    id: String;
    userNo: string;
    url?: string;
    dataId?: string;
  }
  const TabelData = ref<TableRow[]>([]);

  // 注册私信任务表单
  const [registerFormChat, { setFieldsValue, getFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormChat,
    showActionButtonGroup: false,
  });

  const [chatregisterForm, { getFieldsValue: getFieldsValuefast, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: chatAccountFormSchema,
    showActionButtonGroup: false,
  });

  const [registerFormChatTime, { getFieldsValue: getFieldsValueTime }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormChatTime,
    showActionButtonGroup: false,
  });

  const [
    registerTableModel,
    {
      reload,
      updateTableDataRecord,
      getSelectRows,
      setSelectedRowKeys,
      getForm,
      clearSelectedRowKeys,
    },
  ] = useTable({
    api: getMatchCategoryPageAPI,
    rowKey: 'dataId',
    columns: columnsModels,
    showTableSetting: true,
    bordered: true,
    handleSearchInfoFn(info) {
      return info;
    },
    useSearchForm: true,
    formConfig: {
      schemas: searchFormSchema,
      labelWidth: 120,
      autoSubmitOnEnter: true,
    },
    rowSelection: {
      type: 'checkbox',
      onChange: (selectedRowKeys, selectedRows) => {
        checkNum.value = selectedRowKeys;
      },
    },
  });

  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      updateTableDataRecord(values.id, values);
    } else {
      reload();
    }
  }

  function fetchTemplateDetail(value, option) {
    try {
      const detail = templateList.value.find((item) => item.id === option.key);
      if (detail) {
        setFieldsValue({
          title: detail.title,
          content: detail.content,
          district: detail.district,
          age: detail.age,
          gender: detail.gender,
          audience: detail.audience,
          interest: detail.interest,
        });
      }
    } catch (error) {
      console.error('获取模板详情失败', error);
    }
  }

  async function handleOK() {
    const selectedRows = getSelectRows() as TableRow[];
    if (selectedRows.length == 0) {
      message.error('请先选择视频');
      return;
    }
    let links: string[] = [];
    selectedRows.forEach((row) => {
      if (!row.url) {
        const matchedRow = TabelData.value.find((item) => item.dataId === row.dataId);
        if (matchedRow && matchedRow.url) {
          links.push(matchedRow.url);
        }
      } else {
        links.push(row.url);
      }
    });

    if (selectValue.value == 'Video') {
      const deviceLabels = getFieldsValueTime()
        .devices.map((deviceId) => {
          const device = deviceList.value.find((d) => d.value === deviceId);
          return device ? device.label : '';
        })
        .filter((label) => label !== '');
      const devicesString = deviceLabels.join(', ');
      const videoFromData = videoFromRef.value.getData();
      const data = await createTaskApi({
        ...videoFromData,
        links: links,
        devices: devicesString,
        ...getFieldsValueTime,
      });
      message.success(t('sys.configuration.succesSubmit'));
    } else {
      const form = getForm();
      const searchFormValues = await form.getFieldsValue();
      const params = {
        ...getFieldsValue(),
        links: links,
        category: searchFormValues.category,
      };
      const data = await SubcreateTaskAPI(params);
      message.success(t('sys.configuration.succesSubmit'));
    }
  }

  onMounted(async () => {
    try {
      const response = await getAudiencesListAPI();
      templateList.value = response.data;
      const deviceresponse = await getdeviceToOwnerAPI();
      deviceList.value = deviceresponse.data;
    } catch (error) {
      console.error('获取模板列表失败', error);
    }
  });

  async function check() {
    loading.value = true;
    const form = getForm();
    const searchFormValues = await form.getFieldsValue();
    const data = await getMatchCategoryPageAPICheck({
      ...searchFormValues,
      current: 1,
      size: dataIdList.value,
    });
    TabelData.value = data.items;
    const dataIdArray: string[] = [];
    if (Array.isArray(data.items)) {
      data.items.forEach((item) => {
        if (item.dataId) {
          dataIdArray.push(item.dataId);
        }
      });
    }
    setSelectedRowKeys(dataIdArray);
    loading.value = false;
  }

  async function Clear() {
    clearSelectedRowKeys();
  }

  async function handleOKfast() {
    try {
      // 验证表单字段
      const values = await validate();

      // 如果验证通过，继续执行后续操作
      loading.value = true;
      let params = { ...getFieldsValuefast() };

      if (params.devices) {
        const deviceLabels = params.devices
          .map((deviceId) => {
            const device = deviceList.value.find((d) => d.value === deviceId);
            return device ? device.label : '';
          })
          .filter((label) => label !== '');
        const devicesString = deviceLabels.join(', ');

        let pageSize = params.devices.length * 80;
        let page = 1;
        let videoData = await getMatchCategoryPageAPI({
          pageSize: pageSize,
          page: page,
          category: params.category,
          matching: 0,
        });

        let personnelData = await getCommentMarchPageAPI({
          pageSize: pageSize,
          page: page,
          category: params.category,
          matching: 0,
        });

        let links = videoData.items.map((record) => record.url);

        let videoTask = await createTaskApi({
          comments: [{ content: params.content }],
          links: links,
          devices: devicesString,
          interval: 144,
        });

        let userNos = personnelData.items.map((record) => record.userNo);
        let personTask = await createTaskChat({
          title: params.category,
          content: params.Chatcontent,
          userNos: userNos,
          devices: devicesString,
          interval: 144,
        });
        loading.value = false;
        message.success('提交完成,您到任务列表查看具体信息');
      }
    } catch (error) {
      // 如果验证失败，显示错误信息
      console.error('表单验证失败', error);
      message.error('请完善信息');
      loading.value = false;
    }
  }
</script>
<style scoped>
  .left-panel {
    padding: 16px 0 0 16px;
  }

  .left-card {
    height: 100vh;
  }

  .task-type-selector {
    margin-bottom: 20px;
    display: flex;
  }

  .task-type-label {
    margin-right: 10px;
    width: 100px;
    text-align: right;
    line-height: 20px;
  }

  .fast-task {
    margin-top: 10px;
  }

  .selected-video-info {
    margin-left: 30px;
  }

  .task-button-container {
    text-align: center;
  }

  .right-panel {
    padding: 16px 16px 0 16px;
  }

  .toolbar {
    display: flex;
    align-items: center;
    justify-content: space-around;
  }

  .toolbar-label {
    margin-right: 10px;
  }

  .toolbar-input {
    width: 20%;
  }
</style>
